package com.ljph.jfinal.render;

import com.jfinal.kit.LogKit;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;
import com.jfinal.render.RenderFactory;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

/**
 * Created by yuzhou on 16/10/25.
 */
public class GifRender extends Render {
  private File file;

  public GifRender(File file) {
    if (file == null) {
      throw new IllegalArgumentException("file can not be null.");
    }
    this.file = file;
  }

  @Override
  public void render() {
    if (file == null || !file.isFile()) {
      RenderFactory.me().getErrorRender(404).setContext(request, response).render();
      return ;
    }

//    response.setHeader("Pragma","no-cache");
//    response.setHeader("Cache-Control","no-cache");
    response.setDateHeader("Expires", new Date().getTime() + 1000*60*60*24*7);
    // response.setContentType("image/gif");
    Path path = Paths.get(file.getAbsolutePath());
    try {
      response.setContentType(Files.probeContentType(path));
    } catch (IOException e1) {
      response.setContentType("image/gif");
      e1.printStackTrace();
    }
    response.setHeader("Content-Length", String.valueOf(file.length()));

    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
      inputStream = new BufferedInputStream(new FileInputStream(file));
      outputStream = response.getOutputStream();
      byte[] buffer = new byte[1024];
      for (int len = -1; (len = inputStream.read(buffer)) != -1;) {
        outputStream.write(buffer, 0, len);
      }
      outputStream.flush();
    } catch (IOException e) {
      if (getDevMode()) {
        throw new RenderException(e);
      }
    } catch (Exception e) {
      throw new RenderException(e);
    } finally {
      if (inputStream != null)
        try {inputStream.close();} catch (IOException e) {LogKit.error(e.getMessage(), e);}
      if (outputStream != null)
        try {outputStream.close();} catch (IOException e) {LogKit.error(e.getMessage(), e);}
    }
  }
}
